package cn.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.easybuy.entity.MyOrder;
import cn.easybuy.entity.User;
import cn.easybuy.service.BuyCarService;
import cn.easybuy.service.UserService;
import cn.easybuy.service.impl.BuyCarServiceImpl;
import cn.easybuy.service.impl.UserServiceImpl;

import com.alibaba.fastjson.JSON;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public UserServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		BuyCarService buyCarService=new BuyCarServiceImpl();
		UserService userservice = new UserServiceImpl();
		HttpSession session = request.getSession();
		String opr = request.getParameter("opr");
		if ("login".equals(opr)) {
			String userName = request.getParameter("user");
			String pwd = request.getParameter("pwd");
			String check = request.getParameter("check");
			try {
				User user = userservice.loginUser(userName, pwd);
				if (user.getLoginName() != null) {
					if ("true".equals(check)) {
						Cookie cookie = new Cookie("userName", userName);
						cookie.setMaxAge(60 * 60 * 24 * 7);
						response.addCookie(cookie);
						Cookie cookie2 = new Cookie("pwd", pwd);
						cookie2.setMaxAge(60 * 60 * 24 * 7);
						response.addCookie(cookie2);
						session.setAttribute("userName", userName);
						session.setAttribute("pwd", pwd);
					} else {
						Cookie newCookie = new Cookie("userName", ""); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚圭憰浣稿灩闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归柨鐔诲▏閻氱氮erName闁跨喐鏋婚幏绋okie
						newCookie.setMaxAge(1); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崚鐘绘晸閺傘倖瀚归柨鐔告灮閹凤拷
						response.addCookie(newCookie); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崘娆撴晸鐠囶偓绱濋柨鐔告灮閹风兘鏁撻弬銈嗗闁跨喐鏋婚幏铚傜閸撳秹鏁撻弬銈嗗
						Cookie newCookie1 = new Cookie("pwd", ""); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚圭憰浣稿灩闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归柨鐔诲▏閻氱氮erName闁跨喐鏋婚幏绋okie
						newCookie1.setMaxAge(1); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崚鐘绘晸閺傘倖瀚归柨鐔告灮閹凤拷
						response.addCookie(newCookie1); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崘娆撴晸鐠囶偓绱濋柨鐔告灮閹风兘鏁撻弬銈嗗闁跨喐鏋婚幏铚傜閸撳秹鏁撻弬銈嗗
						session.setAttribute("userName", userName);
						session.setAttribute("pwd", pwd);
					}
					session.setAttribute("type", user.getType());
					String userName1 = (String) session.getAttribute("userName");
					if (userName1 != null) {
						List<MyOrder> myOrderlist=(List<MyOrder>) session.getAttribute("carList1");
						List<MyOrder> buyCarlist=(List<MyOrder>) session.getAttribute("buyCarlist");
						if(myOrderlist!=null){
							int carid=-1;
						for (MyOrder myOrder : myOrderlist) {
							for (MyOrder myOrder1 : buyCarlist) {
								if(myOrder.getType_id()==myOrder1.getType_id()){
									int shu=myOrder.getQuantity();
									int shu1=myOrder1.getQuantity();
									float price1=myOrder.getPrice();
									myOrder.setQuantity(shu+shu1);
									myOrder.setCost(myOrder.getQuantity()*price1);
									carid=myOrder1.getId();
									myOrder.setDelproductId(carid);
								}
							}
							myOrder.setLoginName((String)session.getAttribute("userName"));
						}
						session.setAttribute("carList1", null);
						try {
							int falg=buyCarService.setBuyCar(myOrderlist);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					out.print("<script>location.href = 'Index.jsp';</script>");
				} else {
					out.print("<script>alert('用户名或密码是有误！');location.href = 'Login.jsp';</script>");
					/*
					 * response.sendRedirect("Login.jsp");
					 */}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if("exit".equals(opr)){
			Cookie newCookie = new Cookie("userName", ""); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚圭憰浣稿灩闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归柨鐔诲▏閻氱氮erName闁跨喐鏋婚幏绋okie
			newCookie.setMaxAge(0); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崚鐘绘晸閺傘倖瀚归柨鐔告灮閹凤拷
			response.addCookie(newCookie); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崘娆撴晸鐠囶偓绱濋柨鐔告灮閹风兘鏁撻弬銈嗗闁跨喐鏋婚幏铚傜閸撳秹鏁撻弬銈嗗
			Cookie newCookie1 = new Cookie("pwd", ""); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚圭憰浣稿灩闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归柨鐔诲▏閻氱氮erName闁跨喐鏋婚幏绋okie
			newCookie1.setMaxAge(0); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崚鐘绘晸閺傘倖瀚归柨鐔告灮閹凤拷
			response.addCookie(newCookie1); // 闁跨喐鏋婚幏鐑芥晸閺傘倖瀚归崘娆撴晸鐠囶偓绱濋柨鐔告灮閹风兘鏁撻弬銈嗗闁跨喐鏋婚幏铚傜閸撳秹鏁撻弬銈嗗
			session.setAttribute("userName", null);
			session.setAttribute("pwd", null);
			out.print("true");

/*			out.print(session.getAttribute("userName"));
*/		}else if ("yan".equals(opr)) {
			String loginName = request.getParameter("loginName");
			try {
				int result = userservice.loginNameNum(loginName);
				out.print(JSON.toJSONString(result));
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("regist".equals(opr)) {
			User user = new User();
			user.setUserName(request.getParameter("userName"));
			user.setLoginName(request.getParameter("loginName"));
			user.setPassword(request.getParameter("pwd"));
			user.setSex(new Integer(request.getParameter("sex")));
			user.setIdentityCode(request.getParameter("identityCode"));
			user.setEmail(request.getParameter("email"));
			user.setMobile(request.getParameter("mobile"));
			user.setType(0);
			out.flush();
			try {
				int result = userservice.registerUser(user);
				if (result > 0) {
					out.print("<script> alert('濞夈劌鍞介幋鎰'); location.href='/easybuy/Login.jsp';</script>");
				} else {
					out.print("<script> alert('濞夈劌鍞芥径杈Е'); location.href='/easybuy/Regist.jsp';</script>");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("Verification".equals(opr)) {
			String userName = (String) session.getAttribute("userName");
			if (userName == null) {
				response.sendRedirect("Login.jsp");
			} else {
				
				if("insert".equals(request.getParameter("sql"))){
						List<MyOrder> myOrderlist=(List<MyOrder>) session.getAttribute("carList1");
						List<MyOrder> buyCarlist=(List<MyOrder>) session.getAttribute("buyCarlist");
						if(myOrderlist!=null){
							int carid=-1;
						for (MyOrder myOrder : myOrderlist) {
							for (MyOrder myOrder1 : buyCarlist) {
								if(myOrder.getType_id()==myOrder1.getType_id()){
									int shu=myOrder.getQuantity();
									int shu1=myOrder1.getQuantity();
									float price1=myOrder.getPrice();
									myOrder.setQuantity(shu+shu1);
									myOrder.setCost(myOrder.getQuantity()*price1);
									carid=myOrder1.getId();
									myOrder.setDelproductId(carid);
								}
							}
							myOrder.setLoginName((String)session.getAttribute("userName"));
						}
						session.setAttribute("carList1", null);
						try {
							int falg=buyCarService.setBuyCar(myOrderlist);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						}
					}
				String shopCar=request.getParameter("shopcar");
				String totalScore=request.getParameter("totalScore");
				String totalPrice=request.getParameter("totalPrice");
				String page = request.getParameter("page");
				response.sendRedirect("BuyCarServlet?opr=buyCarlist&page="
						+ page+"&shopcar="+shopCar+"&totalPrice="+totalPrice+"&totalScore="+totalScore);
			}
		} else if ("selectAllUser".equals(opr)) {
			int type=(Integer)session.getAttribute("type");
			if(type==1){
				List<User> userList = new ArrayList<User>();
				try {
					userList = userservice.selectAll();
				} catch (Exception e) {
					e.printStackTrace();
				}
				request.setAttribute("userList", userList);
				request.getRequestDispatcher("Member_Collect.jsp").forward(request,
						response);
			}else{
				out.print("<script> alert('权限不足，无法查看');location.href='Member.jsp';</script>");
			}
		} else if ("userinfo".equals(opr)) {
			String name = request.getParameter("loginName");
			List<User> userList = new ArrayList<User>();
			try {
				userList = userservice.selectUserInfo2(name);
				request.getSession().setAttribute("userList", userList);
				request.getRequestDispatcher("Member_User.jsp").forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("selectId".equals(opr)) {
			String id = request.getParameter("id");
			List<User> userList = new ArrayList<User>();
			try {
				userList = userservice.selectUser(new Integer(id));
				User user = new User();
				for (User u : userList) {
					user.setLoginName(u.getLoginName());
					user.setUserName(u.getUserName());
					user.setIdentityCode(u.getIdentityCode());
					user.setEmail(u.getEmail());
					user.setMobile(u.getMobile());
					user.setId(u.getId());
				}
				request.setAttribute("user", user);
				request.getRequestDispatcher("updateUser.jsp").forward(request,
						response);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("mohu".equals(opr)) {
			String userName = request.getParameter("userName");
			List<User> userList = new ArrayList<User>();
			try {
				userList = userservice.selectUser(userName);
				request.setAttribute("userList", userList);
				request.getRequestDispatcher("Member_Collect.jsp").forward(
						request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("delUser".equals(opr)) {
			String id1 = request.getParameter("id");
			int id = new Integer(id1);
			int result = 0;
			try {
				result = userservice.delUser(id);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (result != 0) {
				out.print("<script type='text/javascript'>alert('閸掔娀娅庨幋鎰');location='UserServlet?opr=selectAllUser';</script>");
			} else {
				out.print("<script type='text/javascript'>alert('閸掔娀娅庢径杈Е');</script>");
			}
		} else if ("updateUser".equals(opr)) {
			String loginName = request.getParameter("loginName");
			String userName = request.getParameter("userName");
			String identityCode = request.getParameter("identityCode");
			String mobile = request.getParameter("mobile");
			String email = request.getParameter("email");
			String type = request.getParameter("type");
			String id = request.getParameter("id");
			User user = new User();
			user.setId(new Integer(id));
			user.setLoginName(loginName);
			user.setUserName(userName);
			user.setIdentityCode(identityCode);
			user.setMobile(mobile);
			;
			user.setEmail(email);
			user.setType(new Integer(type));
			int result = 0;
			try {
				result = userservice.updateUser(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (result != 0) {
				out.print("<script type='text/javascript'>alert('闁跨喓娼鹃弨瑙勫灇閻у憡瀚归柨鐔告灮閹凤拷);location='UserServlet?opr=selectAllUser';</script>");
			} else {
				out.print("<script type='text/javascript'>alert('闁跨喓娼鹃棃鈺傚婢堕亶鏁撻弬銈嗗');</script>");
			}
		} else if ("selectPwd".equals(opr)) {
			String id = request.getParameter("id");
			List<User> userList = new ArrayList<User>();
			try {
				userList = userservice.selectUser(new Integer(id));
				request.setAttribute("userList", userList);
				request.getRequestDispatcher("updatePwd.jsp").forward(request,
						response);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if ("updatePwd".equals(opr)) {
			String id = request.getParameter("id");
			String pwd = request.getParameter("password");
			int result = 0;
			try {
				result = userservice.updatePwd(new Integer(id), pwd);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (result != 0) {
				out.print("<script type='text/javascript'>alert('修改成功');location='Login.jsp';</script>");
			} else {
				out.print("<script type='text/javascript'>alert('修改失败');</script>");
			}
		} else if ("addUser".equals(opr)) {
			String loginName = request.getParameter("loginName");
			String password = request.getParameter("password");
			String userName = request.getParameter("userName");
			String identityCode = request.getParameter("identityCode");
			String mobile = request.getParameter("mobile");
			String email = request.getParameter("email");
			String type = request.getParameter("type");
			String sex = request.getParameter("sex");
			User user = new User();
			user.setLoginName(loginName);
			user.setPassword(password);
			user.setUserName(userName);
			user.setIdentityCode(identityCode);
			user.setMobile(mobile);
			user.setEmail(email);
			user.setType(new Integer(type));
			if ("闁跨喐鏋婚幏锟�".equals(sex)) {
				user.setSex(1);
			} else if ("婵傦拷".equals(sex)) {
				user.setSex(0);
			}
			int result = 0;
			try {
				result = userservice.addUser(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (result != 0) {
				out.print("<script type='text/javascript'>alert('闁跨喐鏋婚幏閿嬫Ё閺呮帡鏁撻弬銈嗗闁跨噦鎷�;location='UserServlet?opr=selectAllUser';</script>");
			} else {
				out.print("<script type='text/javascript'>alert('闁跨喐鏋婚幏鐑芥晸缂佺倯宥嗗闁跨噦鎷�;</script>");
			}
		}
		out.flush();
		out.close();
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
